<template>
  <div class="page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <h2>⚠️ 违规违纪管理</h2>
        <p class="page-subtitle">管理学生违规违纪记录，包括记录登记、处理跟踪等</p>
      </div>
      <div class="page-actions">
        <el-button type="success" @click="openAddModal">
          <el-icon><Plus /></el-icon>
          新增记录
        </el-button>
        <el-button @click="refreshViolations">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>


    <!-- 内容卡片 -->
    <div class="content-card">
      <!-- 搜索和筛选 -->
      <div class="card-header">
        <div class="search-section">
          <el-input
            v-model="searchQuery"
            placeholder="搜索违规描述、房间ID..."
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input> 
          <el-button type="primary" @click="handleSearch" style="margin-left: 12px">
            <el-icon><Search /></el-icon>
            搜索
          </el-button> 
        </div>
      </div>

      <!-- 违规记录列表 -->
      <div class="table-container">
        <el-table 
          :data="filteredViolations" 
          style="width: 100%"
          stripe
          border
          v-loading="loading"
        >
          <el-table-column label="违规描述" min-width="200">
            <template #default="{ row }">
              <div class="description">
                <p class="description-text">{{ row.des }}</p>
                <p v-if="row.roomId" class="location">
                  <el-icon><Location /></el-icon>
                  房间ID: {{ row.roomId }}
                </p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="扣分" width="80">
            <template #default="{ row }">
              <span class="score-value">{{ row.score || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="学期" width="100">
            <template #default="{ row }">
              <span class="semester-value">{{ row.semester || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="160">
            <template #default="{ row }">
              <span class="record-date">{{ formatDateTime(row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" type="primary" @click="viewViolation(row)">
                  <el-icon><View /></el-icon>
                  查看
                </el-button>
                <el-button 
                  size="small" 
                  type="warning" 
                  @click="editViolation(row)"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  @click="deleteViolation(row)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalViolations"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑违规记录模态框 -->
    <el-dialog
      v-model="showAddModal"
      :title="showEditModal ? '✏️ 编辑违规记录' : '➕ 新增违规记录'"
      width="600px"
      :before-close="closeAddModal"
    >
      <el-form :model="violationForm" label-width="100px">
        <el-form-item label="违规描述" required>
          <el-input
            v-model="violationForm.des"
            type="textarea"
            :rows="4"
            placeholder="请详细描述违规情况..."
          />
        </el-form-item>
        <el-form-item label="楼栋" required>
          <el-select
            v-model="violationForm.buildingId"
            placeholder="请选择楼栋"
            style="width: 100%"
            @change="onBuildingChange"
          >
            <el-option
              v-for="building in buildings"
              :key="building.id"
              :label="building.name"
              :value="building.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间" required>
          <el-select
            v-model="violationForm.roomId"
            placeholder="请选择房间"
            style="width: 100%"
            :disabled="!violationForm.buildingId"
          >
            <el-option
              v-for="room in availableRooms"
              :key="room.id"
              :label="room.roomNumber"
              :value="room.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="管理员ID" required>
          <el-input
            v-model="violationForm.adminId"
            placeholder="请输入管理员ID"
          />
        </el-form-item>
        <el-form-item label="扣分数值">
          <el-input-number
            v-model="violationForm.score"
            :min="0"
            :max="100"
            placeholder="扣分数值"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="学期">
          <el-input
            v-model="violationForm.semester"
            placeholder="如：20251"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAddModal">取消</el-button>
          <el-button type="primary" @click="handleAddViolation">
            <el-icon><Check /></el-icon>
            保存记录
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search, View, Edit, Delete, Check, Location } from '@element-plus/icons-vue'
import { 
  queryViolationAPI, 
  addViolationAPI, 
  updateViolationAPI, 
  deleteViolationAPI,
  queryViolationByIdAPI 
} from '@/apis/violationAPI'
import { queryDormBuild } from '@/apis/roomBuildAPI'
import { queryRoomAPI } from '@/apis/roomAPI'
import { useAuthStore } from '@/stores/auth'

// 获取当前登录用户
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalViolations = ref(0)
const showAddModal = ref(false)
const showEditModal = ref(false)
const selectedViolation = ref(null)
const violations = ref([])
const buildings = ref([])
const rooms = ref([])

// 违规记录表单
const violationForm = ref({
  id: undefined,
  des: '',
  buildingId: '',
  roomId: '',
  adminId: '',
  score: 0,
  semester: ''
})

// 根据选择的楼栋筛选可用房间
const availableRooms = computed(() => {
  if (!violationForm.value.buildingId) return []
  return rooms.value.filter(room => String(room.buildingId) === String(violationForm.value.buildingId))
})

// 楼栋改变时清空房间选择
const onBuildingChange = () => {
  violationForm.value.roomId = ''
}

// 获取违规记录数据（不使用分页查询，获取全部数据）
const fetchViolations = async () => {
  loading.value = true
  try {
    // 只传递筛选条件，不传递分页参数
    const params = {}
    
    console.log('查询违规记录参数:', params)
    const response = await queryViolationAPI(params)
    console.log('违规记录API响应:', response)
    
    if (response.code === 0) {
      // 后端可能直接返回数组，也可能返回对象包含数据
      let records = []
      if (Array.isArray(response.data)) {
        records = response.data
      } else if (response.data && Array.isArray(response.data.records)) {
        records = response.data.records
      } else if (response.data && Array.isArray(response.data.list)) {
        records = response.data.list
      }
      
      // 转换数据格式以匹配前端显示
      violations.value = records.map(record => ({
        id: record.id,
        revision: record.revision || 0,
        des: record.des || '',
        roomId: record.roomId || null,
        score: record.score || 0,
        adminId: record.adminId || '',
        semester: record.semester || '',
        createTime: record.createTime || '',
        updateTime: record.updateTime || ''
      }))
      
      // 更新总数（前端分页的总数）
      totalViolations.value = violations.value.length
    } else {
      ElMessage.error(response.msg || '获取违规记录失败')
      violations.value = []
      totalViolations.value = 0
    }
  } catch (error) {
    console.error('获取违规记录失败:', error)
    ElMessage.error('获取违规记录失败')
    violations.value = []
    totalViolations.value = 0
  } finally {
    loading.value = false
  }
}


// 计算属性 - 前端筛选（因为后端不再分页）
const filteredViolationsList = computed(() => {
  let result = violations.value
  
  // 前端搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(violation => {
      return (violation.des || '').toLowerCase().includes(query) ||
             (violation.roomId ? violation.roomId.toString().toLowerCase().includes(query) : false)
    })
  }
  
  return result
})

// 计算属性 - 前端分页后的数据
const filteredViolations = computed(() => {
  const filtered = filteredViolationsList.value
  // 更新总数
  totalViolations.value = filtered.length
  // 前端分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})


const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const formatDateTime = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 刷新违规记录
const refreshViolations = () => {
  fetchViolations()
}

// 搜索处理（前端搜索，如果后端不支持搜索则使用前端过滤）
const handleSearch = () => {
  currentPage.value = 1
  // 如果后端支持搜索，则调用API；否则使用前端过滤（已在computed中处理）
  fetchViolations()
}

// 查看违规记录详情
const viewViolation = async (violation) => {
  try {
    const response = await queryViolationByIdAPI(violation.id)
    if (response.code === 0) {
      selectedViolation.value = response.data
      // 可以打开详情对话框或显示详情
      ElMessage.info('查看详情功能开发中...')
    }
  } catch (error) {
    console.error('获取违规记录详情失败:', error)
  }
}

// 编辑违规记录
const editViolation = async (violation) => {
  try {
    // 获取完整的违规记录信息
    const response = await queryViolationByIdAPI(violation.id)
    if (response.code === 0 && response.data) {
      const data = response.data
      selectedViolation.value = data
      // 根据 roomId 找到对应的 buildingId
      const room = rooms.value.find(r => String(r.id) === String(data.roomId))
      violationForm.value = {
        id: data.id,
        des: data.des || '',
        buildingId: room ? room.buildingId : '',
        roomId: data.roomId || '',
        adminId: data.adminId || '',
        score: data.score || 0,
        semester: data.semester || ''
      }
    } else {
      // 如果获取详情失败，使用当前数据
      selectedViolation.value = violation
      const room = rooms.value.find(r => String(r.id) === String(violation.roomId))
      violationForm.value = {
        id: violation.id,
        des: violation.des || '',
        buildingId: room ? room.buildingId : '',
        roomId: violation.roomId || '',
        adminId: violation.adminId || '',
        score: violation.score || 0,
        semester: violation.semester || ''
      }
    }
    showEditModal.value = true
    showAddModal.value = true // 复用新增对话框
  } catch (error) {
    console.error('获取违规记录详情失败:', error)
    // 使用当前数据作为备用
    selectedViolation.value = violation
    const room = rooms.value.find(r => String(r.id) === String(violation.roomId))
    violationForm.value = {
      id: violation.id,
      des: violation.des || '',
      buildingId: room ? room.buildingId : '',
      roomId: violation.roomId || '',
      adminId: violation.adminId || '',
      score: violation.score || 0,
      semester: violation.semester || ''
    }
    showEditModal.value = true
    showAddModal.value = true
  }
}

// 删除违规记录
const deleteViolation = async (violation) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除该违规记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    const response = await deleteViolationAPI(violation.id)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      await fetchViolations()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除违规记录失败:', error)
      ElMessage.error('删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 新增违规记录
const handleAddViolation = async () => {
  // 基本验证
  if (!violationForm.value.des) {
    ElMessage.warning('请输入违规描述')
    return
  }
  if (!violationForm.value.buildingId) {
    ElMessage.warning('请选择楼栋')
    return
  }
  if (!violationForm.value.roomId) {
    ElMessage.warning('请选择房间')
    return
  }
  if (!violationForm.value.adminId) {
    ElMessage.warning('请输入管理员ID')
    return
  }

  loading.value = true
  try {
    // 只提交房间ID，不提交buildingId
    const data = {
      des: violationForm.value.des,
      roomId: violationForm.value.roomId || null,
      adminId: violationForm.value.adminId,
      score: violationForm.value.score || 0,
      semester: violationForm.value.semester || ''
    }

    const response = showEditModal.value 
      ? await updateViolationAPI({ id: violationForm.value.id, ...data })
      : await addViolationAPI(data)
    
    if (response.code === 0) {
      ElMessage.success(showEditModal.value ? '更新成功' : '新增成功')
      closeAddModal()
      await fetchViolations()
    } else {
      ElMessage.error(response.msg || (showEditModal.value ? '更新失败' : '新增失败'))
    }
  } catch (error) {
    console.error('保存违规记录失败:', error)
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 分页处理（前端分页，不需要重新请求）
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  // 不需要重新请求，因为数据已经在内存中
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 不需要重新请求，因为数据已经在内存中
}

// 打开新增对话框
const openAddModal = () => {
  showEditModal.value = false
  selectedViolation.value = null
  violationForm.value = {
    id: undefined,
    des: '',
    buildingId: '',
    roomId: '',
    adminId: authStore.user?.id || '',
    score: 0,
    semester: ''
  }
  showAddModal.value = true
}

const closeAddModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  selectedViolation.value = null
  violationForm.value = {
    id: undefined,
    des: '',
    buildingId: '',
    roomId: '',
    adminId: '',
    score: 0,
    semester: ''
  }
}

onMounted(async () => {
  // 初始化数据
  await Promise.all([
    fetchViolations(),
    // 加载所有楼栋
    (async () => {
      try {
        const bRes = await queryDormBuild()
        buildings.value = bRes.data || []
      } catch (error) {
        console.error('获取楼栋列表失败:', error)
      }
    })(),
    // 加载所有房间
    (async () => {
      try {
        const rRes = await queryRoomAPI({ pageNum: 1, pageSize: 999 })
        rooms.value = rRes.data?.records || rRes.data || []
      } catch (error) {
        console.error('获取房间列表失败:', error)
      }
    })()
  ])
})
</script>

<style scoped>
.page {
  width: 100%;
  max-width: 100%;
  padding: 0;
  margin: 0;
}

.page-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-title h2 {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 6px 0;
}

.page-subtitle {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.page-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
  overflow: hidden;
}

.card-header {
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
  background: #f9fafb;
}

.search-section {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.filter-section {
  display: flex;
  gap: 8px;
}

.table-container {
  overflow-x: auto;
}

.student-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.student-name {
  font-weight: 500;
  color: #1f2937;
}

.student-id {
  font-size: 12px;
  color: #6b7280;
}

.room-info {
  font-size: 12px;
  color: #3b82f6;
}

.description {
  max-width: 200px;
}

.description-text {
  font-size: 14px;
  color: #1f2937;
  margin: 0 0 4px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.location {
  font-size: 12px;
  color: #6b7280;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 4px;
}

.record-date {
  color: #6b7280;
  font-size: 14px;
}

.score-value {
  font-weight: 600;
  color: #dc2626;
  font-size: 16px;
}

.semester-value {
  color: #6b7280;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px;
  border-top: 1px solid #e5e7eb;
  background: #f9fafb;
}

.violation-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #1f2937;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 8px;
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
